<!-- 固定头部组件 -->
<template>
  <div>
    <div class="homeHeader">
      <router-link to="/" class="logo">
        <img :src="logopath" style="width:100%" />
      </router-link>
      <div class="class-tab">
        <el-menu
          height="1.6rem"
          :default-active="defaultTab"
          class="el-menu-demo"
          mode="horizontal"
          @select="handleSelect"
        >
          <router-link :to="{path :item.url,query:{get: item.tag, level: 0, type: 0, page: pageinfo}}" exact tag="el-menu-item"
          v-for="item in tab" :index="item.id" :key="item.id">{{item.name}}</router-link>
        </el-menu>
      </div>
      <div class="load" v-show= "current ===0">
        <el-button type="text" @click="login = true">登录</el-button> &nbsp; /
        <el-button type="text" @click="register = true">注册</el-button>
      </div>
      <div class="load" v-show= "current !==0">
        <el-button type="text" @click="goto">{{username}}</el-button> &nbsp; / &nbsp;
        <el-button type="text" @click="outLogin">注销</el-button>
      </div>
      <search></search>
    </div>
    <el-dialog  :visible.sync="login" :close-on-click-modal=false :width="dialogWidth" center>
      <div class="changeButton">
      <el-button type="text" @click="login = true" style="borderBottomColor : #f20d0d ;color: #f20d0d">登录</el-button>
      <el-button type="text" @click="changeButton" >注册</el-button>
      </div>
      <el-form :model="loginForm" :style="{width: formWidth}" :rules="rules" ref="loginForm">
        <el-form-item label="账号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="loginForm.phone" autocomplete="off" maxlength=11 ></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="loginForm.password" autocomplete="new-password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="身份" :label-width="formLabelWidth" prop="type">
          <el-select v-model="loginForm.type" placeholder="请选择登陆身份">
            <el-option label="会员" value="1"></el-option>
            <el-option label="职员" value="2"></el-option>
            <el-option label="老师" value="4"></el-option>
            <el-option label="管理员" value="3"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="toLogin" round>确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="register" :close-on-click-modal=false :width="dialogWidth"  center>
      <div class="changeButton">
        <el-button type="text" @click="changeButton">登录</el-button>
        <el-button type="text" @click="register = true" style="borderBottomColor : #f20d0d ;color: #f20d0d">注册</el-button>
      </div>
      <el-form :model="registerForm"  :style="{width: formWidth}" :rules="rules" ref="registerForm">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="registerForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="registerForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="registerForm.password" autocomplete="off" type="password"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="toRegister" round>确 定</el-button>
      </div>
    </el-dialog>
    <!-- content渲染 -->
    <router-view v-if="isRouterAlive" v-on:toLog="toLog" v-bind:login="login"/>
  </div>
</template>

<script>
import search from '@/components/search'
// 1.引入mapMutations书写更简便，对应vuex的mutations内方法
import { mapMutations, mapState, mapActions } from 'vuex'
export default {
  name: 'homeHeader',
  data () {
    let checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('电话号码不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('电话号码格式不正确'))
          }
        }
      }, 100)
    }
    return {
      isRouterAlive: true,
      defaultTab: '2',
      pageinfo: '1p',
      logopath: 'https://i.loli.net/2019/12/24/ZcJEriBIbqO5wyd.png',
      tab: [
        {
          id: 1,
          name: '免费课程',
          url: '/courseList',
          tag: 'free'
        },
        {
          id: 2,
          name: '付费课程',
          url: '/courseList',
          tag: 'pay'
        },
        {
          id: 3,
          name: '新闻',
          url: '/news'
        },
        {
          id: 4,
          name: '考试',
          url: '/exam'
        }
      ],
      login: false,
      register: false,
      loginForm: {
        phone: '',
        password: '',
        type: ''
      },
      rules: {
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '类型不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      },
      registerForm: {
        phone: '',
        password: '',
        name: ''
      },
      formLabelWidth: '1.3rem',
      dialogWidth: '6.5rem',
      formWidth: '5rem'
    }
  },
  provide () {
    return {
      reload: this.reload
    }
  },
  computed: {
    ...mapState({
      memberNo: 'memberNo',
      current: 'current',
      username: 'name'
    })
  },
  components: {
    search
  },
  methods: {
    // 刷新局部组件
    async reload () {
      this.isRouterAlive = false
      await this.$nextTick()
      this.isRouterAlive = true
      console.log('刷新页面')
    },
    // 2.引入vuex方法
    ...mapMutations(['TOLOGIN1', 'LOGINOUT1', 'EDITMEMBERINFO', 'EDITEMPLOYEEINFO']),
    handleSelect (key, keyPath) {
      console.log(key, keyPath)
    },
    ...mapActions(['isLogin']),
    changeButton () {
      this.login = !this.login
      this.register = !this.register
    },
    toLog (login) {
      this.login = login
    },
    toLogin () {
      this.$refs['loginForm'].validate((valid) => {
        if (valid) {
          this.http.post(this.ports.manage.login, {
            phone: this.loginForm.phone,
            password: this.loginForm.password,
            type: this.loginForm.type
          }, res => {
            if (res.status === 200) {
              let data = res.data.result
              if (data.code === 200) {
                window.localStorage.setItem('token', JSON.stringify(data.token))
                this.$message({
                  showClose: true,
                  message: data.msg,
                  type: 'success'
                })
                this.login = false
                this.isLogin()
              } else if (data.code === 1) {
                this.$message({
                  showClose: true,
                  message: data.msg,
                  type: 'error'
                })
              }
            } else {
              console.log(res)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    toRegister () {
      this.$refs['registerForm'].validate((valid) => {
        if (valid) {
          this.http.post(this.ports.manage.register, {
            phone: this.registerForm.phone,
            password: this.registerForm.password,
            name: this.registerForm.name
          }, res => {
            if (res.status === 200) {
              let data = res.data.result
              console.log(data.code)
              if (data.code === 200) {
                this.$message({
                  showClose: true,
                  message: data.msg + '，请登陆',
                  type: 'success',
                  duration: '1500'
                })
                this.register = false
                setTimeout(() => {
                  this.login = true
                }, 1500)
              } else if (data.code === 1 || data.code === -1) {
                this.$message({
                  showClose: true,
                  message: data.msg,
                  type: 'error'
                })
              }
            } else {
              console.log(res)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    outLogin () {
      localStorage.removeItem('token')
      this.$message({
        showClose: true,
        message: '退出成功',
        type: 'success'
      })
      this.LOGINOUT1()
      // this.$router.push('/')
    },
    goto () {
      if (this.$route.path.slice(1, 15) !== 'personalCenter') {
        if (this.current === '1') {
          this.$router.push('/personalCenter/pcClass')
        } else if (this.current === '2') {
          this.$router.push('/personalCenter/pcNews')
        } else if (this.current === '3') {
          this.$router.push('/personalCenter/pcEmployee')
        } else if (this.current === '4') {
          this.$router.push('/personalCenter/myClass?page=1')
        }
      }
    },
    getclassesWrapperWidth(){
      let width = document.body.clientWidth
      this.pageinfo += width >= 1450? 12 : 10
    }
  },
  watch: {
    login: function (val) {
      if (val) {
        this.$refs['loginForm'].resetFields()
      }
    },
    register: function (val) {
      if (val) {
        this.$refs['registerForm'].resetFields()
      }
    }
  },
  mounted: function () {
    this.isLogin()
    this.getclassesWrapperWidth()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='scss' scoped>
  $headheight: 1.2rem;
  .homeHeader {
  width: 100%;
  height: $headheight;
  box-shadow: 0 4px 8px rgba(7, 17, 27, 0.1);
  overflow: hidden;
}
.logo {
  float: left;
  width: 3.2rem;
}
.class-tab {
  float: left;
  min-width: 4.8rem;
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.class-tab > .el-menu-item {
  width: 1.8rem;
  padding: 0 0.3rem;
  height: $headheight;
  line-height: $headheight;
  text-align: center;
  color: #4d555d;
}
.el-menu-item {
  font-size: 0.24rem !important;
}
.load {
  width: 2.5rem;
  float: right;
  height: $headheight;
  font-size: 0.24rem;
  line-height: $headheight;
}
.el-menu--horizontal > .el-menu-item {
  height: $headheight;
  line-height: $headheight;
  color: #2c3e50;
}
.router-link-active{
  border-bottom: 2px solid #f20d0d !important;
  color: #f20d0d !important;
}
.class-tab > .el-menu--horizontal .el-menu-item:not(.is-disabled):focus,
.class-tab > .el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
  color: #f20d0d;
}
/*登陆注册*/
.load > .el-button{
  color: #000;
}
.load > .el-button :hover{
  color: #f20d0d;
}
.changeButton > .el-button{
  width : 1rem;
  color: #000;
  margin-top: -0.6rem;
  margin-bottom: 0.4rem;
  font-size : 19px;
  border-bottom :solid 0.08rem #fff
}
.changeButton > .el-button  :hover{
  color: #f20d0d;
}
.dialog-footer > .el-button{
  width:4.5rem;
  margin-top :-0.5rem;
}
</style>
